package xyz.liuz.edb.heart.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

public class MessageProtocolDecoder extends ReplayingDecoder<Void> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("解码器运行啦");
        int messageType = in.readInt();
        CoorMessageProtocol messageProtocol = new CoorMessageProtocol();
        if(messageType == 858862149){
            byte[] messageByte = new byte[11];
            in.readBytes(messageByte);

            messageProtocol.setMessageType(3);
            messageProtocol.setMessageLength("EDBHEARTBEAT".getBytes().length);
            messageProtocol.setMessage("EDBHEARTBEAT".getBytes(CharsetUtil.UTF_8));

        }else{
            int messageLength = in.readInt();
            byte[] messageByte = new byte[messageLength];
            in.readBytes(messageByte);

            messageProtocol.setMessageType(messageType);
            messageProtocol.setMessageLength(messageLength);
            messageProtocol.setMessage(messageByte);
        }
        out.add(messageProtocol);
    }
}
